package common

import (
	"barrage-go/consts"
	"barrage-go/utils"
	"github.com/gorilla/websocket"
	"sync"
)

var (
	lock      sync.Mutex
	videoMap  = make(map[string][]*websocket.Conn)
	clientMap = make(map[*websocket.Conn]string)
)

func AddClient(videoId string, ws *websocket.Conn) {
	lock.Lock()

	clients, ok := videoMap[videoId]
	if ok {
		clients = append(clients, ws)
		videoMap[videoId] = clients
	} else {
		client := clients
		client = append(client, ws)
		videoMap[videoId] = client
	}
	clientMap[ws] = videoId

	lock.Unlock()
}

func GetVideoMap(videoId string) ([]*websocket.Conn, bool) {
	clients, ok := videoMap[videoId]
	return clients, ok
}

func RemoveClient(ws *websocket.Conn) {
	lock.Lock()

	videoId, ok := clientMap[ws]
	if ok {
		clients, ok := videoMap[videoId]
		if ok {
			for i := 0; i < len(clients); i++ {
				if clients[i] == ws {
					clients = append(clients[:i], clients[i+1:]...)
				}
			}
		}
		utils.Decr(consts.BarrageOnlinePopulation + videoId)
		videoMap[videoId] = clients
		delete(clientMap, ws)
	}

	lock.Unlock()
}
